<?php
namespace Admin\Model;
use Think\Model;

class LogisticsModel extends Model{
	//自动验证
	protected $_validate = array(
		array('name','1,20','公司名称不得为空或大于20位！',self::EXISTS_VALIDATE,'length'),
		array('code','1,30','公司代码不得为空或大于30位！',self::EXISTS_VALIDATE,'length'),
	);
	
	//查询总记录
	public function total(){
		return $this->where($this->map())->count();
	}
	
	//查询所有
	public function all($firstRow){
		return $this->field('id,code,name')
					->where($this->map())
					->order(array('code'=>'ASC'))
					->limit($firstRow,C('PAGE_SIZE'))
					->select();
	}
	
	//查询所有（不分页）
	public function all2(){
		return $this->field('id,name,code')
					->order(array('code'=>'ASC'))
					->select();
	}
	
	//查询一条
	public function one($id=0){
		$map['id'] = $id ? $id : I('get.id');
		return $this->field('name,code')->where($map)->find();
	}
	
	//添加
	public function insert(){
		$data = array(
			'name'=>I('post.name'),
			'code'=>I('post.code')
		);
		if ($this->create($data)){
			if ($this->repeat()) return '此物流已存在！';
			$id = $this->add();
			return $id ? $id : 0;
		}else{
			return $this->getError();
		}
	}
	
	//批量添加
	public function multi(){
		foreach (explode("\r\n",I('post.multi')) as $value){
			$value = explode('|',$value);
			if (count($value) != 2) return '批量添加格式有误！';
			$data = array(
				'name'=>$value[0],
				'code'=>$value[1]
			);
			if ($this->create($data)){
				if ($this->repeat(0,$value[0],$value[1])) return '“'.$value[0].'”物流已存在！';
				$this->add();
			}else{
				return $this->getError();
			}
		}
		return 1;
	}
	
	//修改
	public function update(){
		$data = array(
			'id'=>I('get.id'),
			'name'=>I('post.name'),
			'code'=>I('post.code')
		);
		if ($this->create($data)){
			if ($this->repeat(1)) return '此物流已存在！';
			$id = $this->save();
			return $id ? $id : 0;
		}else{
			return $this->getError();
		}
	}
	
	//删除
	public function remove(){
		$affected_rows = $this->delete(I('get.id'));
		if ($affected_rows) $this->execute('OPTIMIZE TABLE `__PREFIX__logistics`');
		return $affected_rows;
	}
	
	//验证重复
	private function repeat($type=0,$name='',$code=''){
		$map = array(
			'_complex'=>array(
				'name'=>$name ? $name : I('post.name'),
				'code'=>$code ? $code : I('post.code'),
				'_logic'=>'OR'
			)
		);
		if ($type) $map['id'] = array('NEQ',I('get.id'));
		return $this->field('id')->where($map)->find();
	}
	
	//搜索
	private function map(){
		$map = array(
			'_complex'=>array(
				'name'=>array('like','%'.I('get.keyword').'%'),
				'code'=>array('like','%'.I('get.keyword').'%'),
				'_logic'=>'OR'
			)
		);
		return $map;
	}
}